"use client";

import { useState, useEffect } from "react";
import TableSider from "./TableSider";
import HeadBar from "./HeadBar";
import ConnectModal from "./ConnectModal";
import SqlContent from "./SqlContent";

export default function Home() {
  const [isDarkMode, setIsDarkMode] = useState(false);
  const [isSiderVisible, setIsSiderVisible] = useState(true);
  const [isConnectModalOpen, setIsConnectModalOpen] = useState(false);
  const [sqlCode, setSqlCode] = useState(""); // 添加SQL代码状态

  // 初始化时从localStorage读取主题设置
  useEffect(() => {
    const savedTheme = localStorage.getItem("theme");
    if (savedTheme === "dark") {
      setIsDarkMode(true);
    } else if (savedTheme === "light") {
      setIsDarkMode(false);
    } else {
      // 如果没有保存的设置，检查系统偏好
      const prefersDark = window.matchMedia(
        "(prefers-color-scheme: dark)"
      ).matches;
      setIsDarkMode(prefersDark);
    }

    // 读取侧边栏显示状态
    const savedSiderState = localStorage.getItem("siderVisible");
    if (savedSiderState !== null) {
      setIsSiderVisible(savedSiderState === "true");
    }
  }, []);

  // 应用主题到document
  useEffect(() => {
    document.documentElement.setAttribute(
      "data-theme",
      isDarkMode ? "dark" : "light"
    );
    localStorage.setItem("theme", isDarkMode ? "dark" : "light");
  }, [isDarkMode]);

  // 保存侧边栏状态
  useEffect(() => {
    localStorage.setItem("siderVisible", isSiderVisible.toString());
  }, [isSiderVisible]);

  const handleRefresh = () => console.log("refresh");
  const handleCreate = () => console.log("create");
  const handleToggleTheme = () => {
    setIsDarkMode((prev) => !prev);
  };
  const handleToggleSider = () => {
    setIsSiderVisible((prev) => !prev);
  };
  const handleAddConnection = () => {
    setIsConnectModalOpen(true);
  };
  const handleLocalConnection = () => {
    // 处理本地连接逻辑
    console.log("本地连接");
  };
  const handleConnectModalClose = () => {
    setIsConnectModalOpen(false);
  };
  const handleConnectSubmit = (connectionData) => {
    console.log("连接数据:", connectionData);
    // 这里可以添加实际的数据库连接逻辑
  };

  // 处理表名点击事件，生成查询SQL
  const handleTableClick = (tableName) => {
    const querySQL = `SELECT * FROM ${tableName} WHERE 1 = 1;`;
    setSqlCode(querySQL);
  };

  return (
    <div
      className={`app-container ${isDarkMode ? "dark-theme" : "light-theme"}`}
      style={{ height: "100vh" }}
    >
      <div className="d-flex flex-column h-100">
        <HeadBar
          onRefresh={handleRefresh}
          onCreate={handleCreate}
          onToggleTheme={handleToggleTheme}
          onToggleSider={handleToggleSider}
          onAddConnection={handleAddConnection}
          onLocalConnection={handleLocalConnection}
          isDarkMode={isDarkMode}
          isSiderVisible={isSiderVisible}
        />
        <div className="d-flex flex-grow-1 main-layout">
          <div
            className={`sider-container ${
              isSiderVisible ? "visible" : "hidden"
            }`}
          >
            <TableSider
              isDarkMode={isDarkMode}
              isVisible={isSiderVisible}
              onTableClick={handleTableClick}
            />
          </div>
          <div
            className={`content-container ${
              isSiderVisible ? "with-sider" : "full-width"
            }`}
          >
            <SqlContent
              isDarkMode={isDarkMode}
              sqlCode={sqlCode}
              setSqlCode={setSqlCode}
            />
          </div>
        </div>
      </div>

      <style jsx global>{`
        .light-theme {
          --bg-primary: #ffffff;
          --bg-secondary: #f8f9fa;
          --bg-tertiary: #fcfcfc;
          --text-primary: #212529;
          --text-secondary: #6c757d;
          --text-muted: #999999;
          --border-color: #eeeeeee;
          --border-light: #f1f1f1;
          --shadow: rgba(0, 0, 0, 0.1);
        }

        .dark-theme {
          --bg-primary: #1a1a1a;
          --bg-secondary: #2d2d2d;
          --bg-tertiary: #333333;
          --text-primary: #ffffff;
          --text-secondary: #cccccc;
          --text-muted: #888888;
          --border-color: #404040;
          --border-light: #353535;
          --shadow: rgba(0, 0, 0, 0.3);
        }

        .app-container {
          background-color: var(--bg-primary);
          color: var(--text-primary);
          transition: background-color 0.3s ease, color 0.3s ease;
        }

        .main-layout {
          position: relative;
          overflow: hidden;
        }

        .sider-container {
          transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1),
            opacity 0.3s ease;
          flex-shrink: 0;
        }

        .sider-container.visible {
          transform: translateX(0);
          opacity: 1;
        }

        .sider-container.hidden {
          transform: translateX(-100%);
          opacity: 0;
          width: 0;
          overflow: hidden;
        }

        .content-container {
          flex: 1;
          min-width: 0;
          transition: margin-left 0.3s cubic-bezier(0.4, 0, 0.2, 1);
          background-color: var(--bg-primary);
          color: var(--text-primary);
        }

        .content-container.with-sider {
          margin-left: 0;
        }

        .content-container.full-width {
          margin-left: 0;
        }

        .main-content {
          background-color: var(--bg-primary);
          color: var(--text-primary);
          height: 100%;
          overflow-y: auto;
        }

        .dark-theme .alert-info {
          background-color: var(--bg-tertiary);
          border-color: var(--border-color);
          color: var(--text-primary);
        }

        .dark-theme .alert-info .alert-heading {
          color: var(--text-primary);
        }

        .dark-theme .alert-info hr {
          border-color: var(--border-color);
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
          .sider-container.visible {
            position: absolute;
            top: 0;
            left: 0;
            height: 100%;
            z-index: 50;
            box-shadow: 2px 0 8px var(--shadow);
          }
        }
      `}</style>

      {/* ConnectModal */}
      <ConnectModal
        isOpen={isConnectModalOpen}
        onClose={handleConnectModalClose}
        onSubmit={handleConnectSubmit}
        isDarkMode={isDarkMode}
      />
    </div>
  );
}
